package com.cloudxingkong.dianyinke.Student.Fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Fragment.BaseFragment;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Adapter.FuJinLaoShiAdapter;
import com.cloudxingkong.dianyinke.Student.Ui.CourseBooking;
import com.cloudxingkong.dianyinke.Student.bean.FuJinLaoShi;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 附近老师Fragment
 */
public class FuJinLaoShiFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, FuJinLaoShiAdapter.onTouchItemPosition {
	private ListView listView;
	private FuJinLaoShiAdapter adapter;
	private List<FuJinLaoShi.ListBean> list;
	private SharedPreferences sharedPreferences;
	private SwipeRefreshLayout swipeRefreshLayout;
	private boolean isAddr = false;
	private View view;
	private int mPosition;
	private String latitude;
	private String longitude;
	private String kemu;

	@Override
	public View onCreateView (final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate (R.layout.fragment_fu_jin_lao_shi, null);
		init ();
		return view;
	}

	private void init () {
		listView = (ListView) view.findViewById (R.id.lv_fujinglaoshi);
		list = new ArrayList<> ();
		adapter = new FuJinLaoShiAdapter (list, getContext (), this);
		listView.setAdapter (adapter);
		swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById (R.id.fjls_swiperefresh);

		swipeRefreshLayout.setColorSchemeResources (R.color.main,
				android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
		swipeRefreshLayout.setOnRefreshListener (this);
	}

	private void loadData () {
		list.clear ();
		kemu = sharedPreferences.getString ("kemu", "");
		longitude = sharedPreferences.getString ("latitude", "");
		latitude = sharedPreferences.getString ("longitude", "");

		final String sessionID = CookieHelper.getSessionID (sharedPreferences);
		final String upLoadUrl = ThisUri.SERVER_YUMING + StudentUri.FUJINLAOSHI;
		RequestParams params = new RequestParams (upLoadUrl);
		params.addHeader ("cookie", sessionID);
		params.setMultipart (true);
		params.addBodyParameter ("order", "pos");//按经纬度查老师
		params.addBodyParameter ("posx", "11.2551");
		params.addBodyParameter ("posy", "154.452124");
		params.addBodyParameter ("subject", kemu);


		x.http ().post (params, new Callback.CommonCallback<String> () {
			@Override
			public void onSuccess (String result) {
				Log.e ("test", "附近的苍老师 " + result);
				try {
					if (result != null && !result.equals ("")) {
						Message msg = handler.obtainMessage ();
						msg.what = 1;
						msg.obj = result;
						handler.sendMessage (msg);
					} else {
						handler.sendEmptyMessage (2);
					}
				} catch (Exception e) {
					Log.e ("test", "fujin " + e.getMessage ());
				}

			}

			@Override
			public void onError (Throwable ex, boolean isOnCallback) {
				handler.sendEmptyMessage (3);
			}

			@Override
			public void onCancelled (CancelledException cex) {

			}

			@Override
			public void onFinished () {
				swipeRefreshLayout.setRefreshing (true);
			}
		});
	}

	private Handler handler = new Handler () {
		@Override
		public void handleMessage (Message msg) {
			super.handleMessage (msg);
			switch (msg.what) {
				case 1:
					String state = (String) msg.obj;
					if (state != null && !state.equals ("")) {

						Log.e ("test", "附近老师:" + state);
						Gson gson = new Gson ();
						FuJinLaoShi entity = null;
						entity = gson.fromJson (state, FuJinLaoShi.class);

						if (entity.getList ().size () <= 0 || entity.getList () == null) {
							Toast.makeText (getActivity (), "暂无" + kemu + "课程", Toast.LENGTH_SHORT).show ();
							sharedPreferences.edit ().putString ("kemu", "").commit ();
							swipeRefreshLayout.setRefreshing (false);
							return;
						}
						list.addAll (entity.getList ());

						//       Toast.makeText(getActivity(), "获取附近老师成功！", Toast.LENGTH_SHORT).show();
						swipeRefreshLayout.setRefreshing (false);
						adapter.notifyDataSetChanged ();
						try {
							SharedPreferences.Editor edit = sharedPreferences.edit ();
							edit.putString ("kemu", "");
							edit.clear ().commit ();

						} catch (Exception e) {
							Log.e ("test", "fujin laoshi " + e.getMessage ());
						}
					} else {
						Toast.makeText (getActivity (), "获取附近老师失败，请重试！", Toast.LENGTH_SHORT).show ();

					}
					break;
				case 2:
					Toast.makeText (getActivity (), "获取定位信息失败，请稍后再试", Toast.LENGTH_SHORT).show ();
					swipeRefreshLayout.setRefreshing (false);
					sharedPreferences.edit ().putString ("kemu", "").commit ();
					break;
				case 3:
					swipeRefreshLayout.setRefreshing (false);
					Toast.makeText (getActivity (), "获取失败，请重试！", Toast.LENGTH_SHORT).show ();
					sharedPreferences.edit ().putString ("kemu", "").commit ();
					break;
			}
		}
	};

	@Override
	public void onRefresh () {
		loadData ();
	}

	@Override
	public void onTouch (int position) {

		mPosition = position;
	}

	@Override
	public void onDestroy () {

		super.onDestroy ();
	}

	@Override
	public void setUserVisibleHint (boolean isVisibleToUser) {
		super.setUserVisibleHint (isVisibleToUser);
		if (isVisibleToUser) {
			sharedPreferences = getActivity ().getSharedPreferences ("data_dyk", 0);
			//设置自动刷新
			swipeRefreshLayout.post (new Runnable () {
				@Override
				public void run () {
					swipeRefreshLayout.setRefreshing (true);
				}
			});
			loadData ();
			//listView点击事件
			listView.setOnItemClickListener (new AdapterView.OnItemClickListener () {
				@Override
				public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
					Intent intent = new Intent (getActivity (), CourseBooking.class);
					int teacherid = list.get (position).getTeacherid ();
					Log.e ("test", "teacherID " + teacherid);
					intent.putExtra ("teacherID", teacherid + "");
					intent.putExtra ("tMemname", list.get (position).getMemname () + "");
					intent.putExtra ("teacherPIC", list.get (position).getCoverpic () + "");

					startActivity (intent);
				}
			});
		} else {
			return;
		}
	}
}
